//------------------------------------------------------------------------------
#include "application.h"
#include "network/localserver.h"
#include "network/stnmessage.h"
#include "views/mainwindow.h"
#include "stdio.h"

#include <QtGui/QApplication>
#include <QDebug>

#ifdef Q_OS_UNIX
#include <signal.h>
#endif // Q_OS_UNIX

LocalServer *server = 0;
//------------------------------------------------------------------------------
void help(){
	// TODO - Display help
	printf("Help !\n");
}
//------------------------------------------------------------------------------
#ifdef Q_OS_UNIX
void sigHandler(int signal){
	Q_UNUSED(signal);
	//printf("Received signal : %d\n", signal);
	App.quit();
}
#endif // Q_OS_UNIX
//------------------------------------------------------------------------------
bool parseMessageArgs(STNMessage &message){
	QString title, msg, icon, program;

	int args = App.args().length();

	// 3 Args : Exec "Title" "Message"
	if(args == 3){
		title = App.args()[1];
		msg = App.args()[2];
	}
	// More than 3 args
	else if(args > 3){
		for(int i=0 ; i < args ; i++){
			const QString &arg = App.args()[i];

			// Arg : -t "Title"
			if(arg == "-t" && args > (i+1))
				title = App.args()[i+1];
			// Arg : -m "Message"
			else if(arg == "-m" && args > (i+1))
				msg = App.args()[i+1];
			// Arg : -i "Icon"
			else if(arg == "-i" && args > (i+1))
				icon = App.args()[i+1];
			// Arg : -p "Program"
			else if(arg == "-p" && args > (i+1))
				program = App.args()[i+1];
		}
	}

	// Message is valid !
	if(!title.isEmpty() && !msg.isEmpty()){
		message = STNMessage(msg, title, icon, program);
		return true;
	}

	return false;
}
//------------------------------------------------------------------------------
int main(int argc, char *argv[]){
	Application::create(argc, argv);

	App.setQuitOnLastWindowClosed(true);

	STNMessage message;
	int retCode = 0;

	// Help
	if(App.args().contains("--help") || App.args().contains("-h")){
		help();
		return 0;
	}
	else if(App.args().contains("--version") || App.args().contains("-v")){
		printf("%s %s\n", App.applicationName().toStdString().c_str(), App.applicationVersion().toStdString().c_str());
		return 0;
	}
	// Started as server
	else if(App.args().size() == 1 || App.args().contains("--server")){
		server = new LocalServer(DEFAULT_SERVER_NAME, &App);
		if(!server->start())
			return 1;

#ifdef Q_OS_UNIX
		// Handling abort signals
		signal(SIGABRT,	sigHandler); // (Signal Abort) Abnormal termination, such as is initiated by the abort function.
		signal(SIGINT,		sigHandler); // (Signal Interrupt) Interactive attention signal. Generally generated by the application user.
		signal(SIGTERM,	sigHandler); // (Signal Terminate) Termination request sent to program.
#endif // Q_OS_UNIX
	}
	// Started as client, sends message to the server and exits
	else if(parseMessageArgs(message)){
		// Connection to local server
		QLocalSocket sock(&App);
		sock.connectToServer(DEFAULT_SERVER_NAME);

		// Connected to the server
		if(sock.waitForConnected()){
			// Format message
			QString msg = message.toXml();
			// Send it
			sock.write(msg.toStdString().c_str(), msg.length());
			// Wait for it to be sent
			sock.waitForBytesWritten();

			// Then disconnect from the server
			sock.disconnectFromServer();
			if(sock.state() != QLocalSocket::UnconnectedState)
				sock.waitForDisconnected();
		}
		else{
			qWarning()<<"Impossible to connect to server";
			return 1;
		}

		return 0;
	}
	// Unknown args
	else{
		help();
		return 1;
	}

	MainWindow * w = new MainWindow();
	// Do not show on startup, start minimized
	//w->show();

	QObject::connect(w, SIGNAL(quitRequested()), &App, SLOT(quit()));
	if(server)
		QObject::connect(server, SIGNAL(messageReceived(STNMessage)), w, SLOT(displayMessage(STNMessage)));

	retCode = App.exec();

	// Stop server before closing app
	if(server){
		server->stop();
		delete server;
		server = 0;
	}

	delete w;
	Application::destroy();

	return retCode;
}
//------------------------------------------------------------------------------
